package com.ysz.server.task;

import com.ysz.common.struct.ClientStruct;
import com.ysz.server.DynamicGrouping;
import com.ysz.common.util.DynamicGroupingUtil;
import com.ysz.common.util.TimeUtil;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName ContinueScanTask
 * @Description TODO
 * @Data 16:29
 * @Version 1.0
 * @Author ysz
 */
public class ContinueScanTask implements Runnable {

    @Override
    public void run() {
        while (true) {
            try {
                Integer indexByTime = DynamicGroupingUtil.getIndexByTime(TimeUtil.getCurrentTime());
                System.out.println("动态分组当前扫描的节点下标为： " + indexByTime);
                ConcurrentHashMap<Integer, List<ClientStruct>> map = DynamicGrouping.getMAP();
                List<ClientStruct> clientStructs = map.get(indexByTime);
                if (Objects.nonNull(clientStructs) && clientStructs.size() > 0) {
                    clientStructs.removeIf(cli -> {
                        if (bottomLineStrategy(cli.getNextSendTime())) {
                            System.out.println("服务端轮询策略  识别出心跳超时节点准备移除：" + cli.getIp());
                            return true;
                        }
                        return false;
                    });
                }
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 兜底策略 判断当前时间跟客户端下一次发送的时间，如果
     * 当前时间isAfter nextSendTime  那么就可以认定该节点超时了
     *
     * @author ysz
     * @date 2022/3/3 17:05
     */
    private boolean bottomLineStrategy(LocalDateTime nextSendTime) {
        return LocalDateTime.now().isAfter(nextSendTime);
    }
}
